package cn.dgut.FrontManger;

import cn.dgut.Utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet("/ModifyStudent")
public class ModifyStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        List<String> list = new ArrayList<>();

        Map<String,String> login = (Map<String, String>) request.getSession().getAttribute("isFrontLogin");
        int user_id;
        int count=0;
        if(login!=null){
            user_id = Integer.parseInt(login.get("id"));
        }else {
            user_id = -1;
        }
        if(user_id>0){
            for (Iterator iter = parameterMap.entrySet().iterator(); iter.hasNext(); ) {
                Map.Entry element = (Map.Entry) iter.next();
                String[] value = (String[]) element.getValue();
                for (int i = 0; i < value.length; i++) {
                    list.add(value[i]);
                }
            }

            String sql = "update Student set student_name='"+list.get(0)+"',student_passwd='"+list.get(1)+"',student_phone='"+
                    list.get(2)+"',student_email='"+list.get(3)+"',slevel='"+list.get(4)+"' where student_id = "+user_id;
            JDBCUtils jdbcUtils = new JDBCUtils();
            count = jdbcUtils.querySQL(sql);
            if(count==1){
                Map<String, String> info = new HashMap<String, String>();
                info.put("name", list.get(0));
                info.put("id", String.valueOf(user_id));
                HttpSession session = request.getSession(true);
                session.setAttribute("isFrontLogin", info);
            }
        }
        response.setContentType("application/json,charset=utf-8");
        String strJson = "{\"flag\":\""+count+"\"}";
        response.getWriter().println(strJson);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}